/**
 * Created by leo on 2/2.
 */
angular.module('panels')
    .directive('panelItilNoticeList', function ($http, $timeout, loadConf, LoginInfo, tabService, $log, Promise) {
        return {
            scope: {},
            link: function (scope, elem) {
                var typeColors = ["#7cb5ec", "#90ed7d", "#f7a35c", "#8085e9", "#f15c80", "#e4d354", "#8d4653", "#91e8e1", "#6b8e23", "#ee82ee", "#800080"];
                scope.getTypeColor = function (notice) {
                    var code = 0, typeName = notice.TYPE_NAME || '';
                    for (var i = 0; i < typeName.length; i++) {
                        code += typeName.charCodeAt(i);
                    }
                    return typeColors[code % 100 % typeColors.length];
                };
                scope.notices = [];
                loadConf('panel-itil-notice-list.yml')
                // 获取panel的配置数据
                    .then(function (setting) {
                        scope.openNoticeDetail = function (notice) {
                            tabService.addTab({
                                name: '公告：' + notice.TITLE,
                                url: setting.viewUrl.replace('{PUBLISH_ID}', notice.PUBLISH_ID)
                            });
                        };
                        return Promise.all({setting: setting, loginInfo: LoginInfo});
                    })
                    // 更新noticeList
                    .then(function (result) {
                        var setting = result.setting, loginInfo = result.loginInfo, timeoutId;
                        scope.more = setting.more;
                        scope.$on('$destroy', function () {
                            timeoutId && $timeout.cancel(timeoutId);
                        });
                        (function updateData() {
                            $http.jsonp(setting.listQueryUrl.replace('{userId}', loginInfo.currentUser.LOGIN_ID).replace('{T}',new Date().getTime())).success(function (list) {
                                scope.notices_1 = list.moveList;
                                scope.notices_2 = list.newpublishList;
                            }).then(callback, callback);
                            function callback() {
                                if (setting.updateInterval > 0) {
                                    timeoutId = $timeout(updateData, setting.updateInterval * 1000);
                                }
                            }

                            $log.debug('panel update data: itil-notice-list')
                        }());
                    });
            },
            templateUrl: 'app/panel/itil/notice-list.html'
        };
    });